﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Reflection;

namespace Rule
{
    public class TemplateRuleHalper
    {
        private static int depth = 0;

        public static TemplateRule loadTemplateRule(string fileName)
        {
            FileStream xmlFile = new FileStream(fileName, FileMode.Open);
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlFile);
            XmlElement root = doc.DocumentElement;
            Debug.WriteLine(root.Name);
            TemplateRule rootRule = new TemplateRule();
            XmlNodeList nodes = root.ChildNodes;
            processTemplateRule(nodes, rootRule);
            xmlFile.Close();
            return rootRule;
        }

        protected static bool processTemplateRule(XmlNodeList nodes, TemplateRule parent)
        {
            
            if (nodes != null)
            {
                depth += 1;
                foreach (XmlNode node in nodes)
                {
                    Debug.WriteLine(string.Format("{0} - {1}", depth, node.Name));
                    string className = node.Attributes["class"].Value;
                    Assembly assembly = Assembly.GetExecutingAssembly();
                    Type classType = assembly.GetType(string.Format("Rule.{0}", className));
                    if (classType != null)
                    {
                        TemplateRule rule = assembly.CreateInstance(classType.FullName) as TemplateRule;
                        parent.Rules.Add(rule);
                        if (rule != null)
                        {
                            rule.parseFromXmlNode(node);
                            Debug.WriteLine(rule.ToString());
                        }
                        processTemplateRule(node.ChildNodes, rule);
                    }
                }
                depth -= 1;
            }
            return true;
        }

        public static float mm2Pixel(float mmValue, int dpi)
        {
            return mmValue * dpi / 25.4f;
        }
    }
}
